package com.frx.leetcode.base.arraytest;

/**
 * Created with IDEA
 * @description leetcode 寻找数组的中心索引
 *              输入 [1,7,3,6,5,6]    输出 3   1 + 7 + 3 = 5 + 6
 *              输入[1,2,3]  输出 -1
 * @author: xrf
 * @Date: 2019/7/16
 * @Time: 11:10
 */
public class CenterIndex {

    public static void main(String[] args){
        int[] nums = {5,6,6,1,7,3};
        int[] nums2 = {1,0};
        int[] nums3 = {-1,-1,0,1,1,0};
        int[] nums4 = {-1,-1,-1,1,1,1};
        int[] nums5 = {-1,-1,0,1,1,-1};
        int[] nums6 = {-1,-1,1,1,0,0};
        System.out.println(solution(nums6));
        System.out.println(solution2(nums6));
    }

    /** 暴力迭代法*/
    public static int solution(int[] nums){
        if(nums.length == 0){
            return -1;
        }
        if (sum(nums,1,nums.length) == 0){
            return 0;
        }
            for (int i=0; i < nums.length-1;i++){
                if (sum(nums,0,i) == sum(nums,i+1,nums.length)){
                    return i;
                }
            }
        if (sum(nums,0,nums.length-1) == 0){
            return nums.length-1;
        }
        return -1;
    }

    public static int sum(int[] nums,int a, int b){
        int sum = 0;
        for (int i=a; i<b;i++){
            sum += nums[i];
        }
        return sum;
    }


    /** 整体求和法*/
    public static int solution2(int[] nums){
        // 先对数组整体进行求和
        int sum = 0;
        int leftSum = 0;
        for (int a : nums){
            sum += a;
        }
        for (int i=0;i<nums.length;i++){
            leftSum += nums[i];
            if ((leftSum - nums[i]) == (sum - leftSum)){
                return i;
            }
        }

        return -1;
    }
}
